package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.config.RedisConfig;
import com.reggie.dto.DishDto;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.service.CategoryService;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

//    新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
//        删除指定分类的redis缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

//    分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();
        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
//        添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,lambdaQueryWrapper);

//        拷贝对象
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
//        取出分页中的菜品数据
        List<Dish> record=pageInfo.getRecords();
//        把dish的数据换成dishDto数据,把categoryId换成categoryName
        List<DishDto> list=record.stream().map((item)->{
              DishDto dishDto=new DishDto();
            Category category = categoryService.getById(item.getCategoryId());
             if (category!=null){
                 dishDto.setCategoryName(category.getName());
                 BeanUtils.copyProperties(item,dishDto);
             }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

//    菜品更新的数据回显
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

//    菜品更新
    @PutMapping
    public R<String> update(@RequestBody  DishDto dishDto){
      dishService.updateWithFlavor(dishDto);

//      删除所有redis缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
//        删除指定分类的换成
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

//    @PostMapping("/status/{status}")
//    public R<String> updateStatusStop(Long ids){
//        Dish dish = dishService.getById(ids);
//        dish.setStatus(0);
//        dishService.updateById(dish);
//        return R.success("更新状态成功");
//    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") int status, @RequestParam Long[] ids){
        log.info(ids.toString());
      LambdaQueryWrapper<Dish>  queryWrapper=new LambdaQueryWrapper<>();
      queryWrapper.in(ids !=null,Dish::getId,ids);
        List<Dish> list = dishService.list(queryWrapper);
        if (list!=null){
            for (Dish dish:list){
                dish.setStatus(status);
                dishService.updateById(dish);
//                删除指定类型的redis缓存
                String key="dish_"+dish.getCategoryId()+"_1";
                redisTemplate.delete(key);
            }
            return R.success("状态已修改");
        }

        return R.error("状态修改失败");

    }

    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
       dishService.removeWithFlavor(ids);
//       删除所有redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

//    查询菜品数据
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
////        添加条件 ,状态为1(在售)的菜品
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }

    //    查询菜品数据(增强)
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dtoList=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        先从redis中获取数据
        dtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dtoList!=null){
//            如果存在,直接返回
            return R.success(dtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
//        添加条件 ,状态为1(在售)的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        dtoList=list.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
//            当前菜品的id
             Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> dishDtoQueryWrapper=new LambdaQueryWrapper<>();
            dishDtoQueryWrapper.eq(DishFlavor::getDishId,dishId);

//            查询菜品的口味
            List<DishFlavor> flavorList = dishFlavorService.list(dishDtoQueryWrapper);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dtoList,1, TimeUnit.HOURS);

        return R.success(dtoList);
    }
}
